import { _decorator, Component, Node } from "cc"
import { ClientEvent } from "../framework/ClientEvent"
import { Tween } from "cc"
import { GlobalData } from "../GlobalData"
import { GUIDE_STATE } from "../framework/constant"
import { GuideHand } from "./GuideHand"
import { Vec3 } from "cc"
import ResManager from "../framework/ResManager"
import { Prefab } from "cc"
import { instantiate } from "cc"
const { ccclass, property } = _decorator

@ccclass("GamePlayerDebris")
export class GamePlayerDebris extends Component {
  private roleId: number = 0
  private firstScale: number = 0
  public isTouch: boolean = false

  @property(Node)
  nodeLight: Node = null!

  @property(Node)
  nodeDebris: Node = null!

  protected onEnable(): void {
    this.firstScale = this.node.scaleX
    this.node.alpha = 0
    new Tween(this.node).to(0.05, { alpha: 1 }).start()
    new Tween(this.nodeLight).by(2, { angle: 360 }).repeatForever().start()

    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
  }

  protected onDisable(): void {
    this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this)
    this.unscheduleAllCallbacks()
    Tween.stopAllByTarget(this.node)
  }

  private onTouchStart() {
    if (!this.isTouch) return
    // this.onDisable()
    ClientEvent.emit("onInitPlayerRole", this.roleId, this.node.getPosition())
    this.node.destroy()
  }

  update(deltaTime: number) {}

  public init(roleId: number) {
    //todo:修改对应的颜色
    this.roleId = roleId

    const time1: number = 0.5
    const movePosX: number = Math.min(this.node.positionX + 180, 317)
    new Tween(this.node).to(time1, { positionX: movePosX }).start()
    new Tween(this.node)
      .by(time1 * 0.5, { positionY: 100 }, { easing: "cubicOut" })
      .by(time1 * 0.5, { positionY: -100 }, { easing: "bounceOut" })
      .call(() => {
        this.isTouch = true
        if (GlobalData.instance.gCurrGuide == GUIDE_STATE.NONE) {
          GlobalData.instance.gCurrGuide = GUIDE_STATE.ROLE_DEBRIS
          this.onGuideDebris(this.node)
        }
      })
      .start()

    this.scheduleOnce(() => {
      new Tween(this.nodeDebris)
        .by(0.4, { positionY: 20 })
        .by(0.8, { positionY: -40 })
        .by(0.4, { positionY: 20 })
        .union()
        .repeatForever()
        .start()

        new Tween(this.nodeLight)
        .by(0.4, { positionY: 20 })
        .by(0.8, { positionY: -40 })
        .by(0.4, { positionY: 20 })
        .union()
        .repeatForever()
        .start()
    }, 0.8)
  }

  private onGuideDebris(parent: Node) {
    const nodeGuide = this.createGuideHand()
    const guideHand: GuideHand = nodeGuide.getComponent(GuideHand)
    nodeGuide.parent = parent
    guideHand.initGuideTouch(new Vec3(0, 0))
  }
  private createGuideHand() {
    const prefab: Prefab = ResManager.instance.getRes("prefabs/game/gameObject/guideHand", Prefab)
    return prefab ? instantiate(prefab) : null
  }
}
